# -*- coding: UTF-8 -*-
import sys
import time
import uuid

import json
from config.default_settings import DataBaseConfig
from sqlalchemy import create_engine, Engine, event
from config.logging_config import logger
from model.common_model import Base
from utils.common_util import assert_util_is_true, assert_util_is_false
from utils.exception_util import ErrorCode
from utils.snowflake_util import SnowFlake
from sqlalchemy.orm import sessionmaker, Session as BaseSession



def format_log_statement(statement, parameters:dict):
    for key, value in parameters.items():
        column_name= "%({column_name})s".format(column_name=key)
        column_value = value if value is not None else 'null'
        statement = statement.replace(column_name,column_value)
    return statement



@event.listens_for(Engine, "after_cursor_execute")
def sqlalchemy_after_cursor_execute(conn, cursor, statement, parameters, context, executemany):
    duration = time.time() - getattr(context, 'sqlalchemy_start_time', None)
    info = format_log_statement(statement, parameters)
    logger.info(f"耗时：{duration:.4f}s\n"+info)



@event.listens_for(Engine, "before_cursor_execute")
def sqlalchemy_before_cursor_execute(conn, cursor, statement, parameters, context, executemany):
    context.sqlalchemy_start_time = time.time()


class SqlalchemyHelper(object):
    def __init__(self, data_base_config: DataBaseConfig, **kwargs):
        self.connect_url = data_base_config.get_connect_url()
        self.engine = create_engine(url=self.connect_url, **kwargs)
        # 创建 Session 工厂
        self.Session = sessionmaker(bind=self.engine, autocommit=False)
        self.snowflake = SnowFlake(datacenter_id=1, worker_id=2, sequence=0)

    def get_session(self):
        # 手动获取连接
        return self.Session()

    def get_engine(self):
        return self.engine

    def save(self, entity: Base):
        # 创建会话
        custom_session = self.get_session()
        try:
            custom_session.add(entity)
            custom_session.commit()
        except Exception as e:
            custom_session.rollback()
            logger.error(e)
        finally:
            # 关闭会话
            custom_session.close()

    def save_batch(self, entitys: list):
        # 创建会话
        custom_session = self.get_session()
        try:
            custom_session.add_all(entitys)
            custom_session.commit()
        except Exception as e:
            custom_session.rollback()
            logger.error(e)
        finally:
            # 关闭会话
            custom_session.close()

    def get_list(self, class_name):
        # 基类校验
        assert_util_is_false(issubclass(class_name, Base), ErrorCode.UNKNOWN_ERROR_CODE.value)
        # primary_key_list= class_name.__table__.primary_key.columns.keys()
        # 创建会话
        custom_session = self.get_session()
        try:
            return custom_session.query(class_name).all()
        except Exception as e:
            logger.error(e)
        finally:
            # 关闭会话
            custom_session.close()

    def get_snowflake_id(self):
        return self.snowflake.get_snowflake_id()

    def force_dict(self,obj:Base):
        return {c.name: getattr(obj, c.name) for c in obj.__table__.columns}

    def force_list(self,data_list):
        return [self.force_dict(item) for item in data_list]
    def to_json(self,data_list):
        return json.dumps(self.force_list(data_list))

